<?php
/**
 * represents a <a> control
 */
fily_XMLConverter::registerNamespace('link', fily_Link);
class fily_Link extends fily_ControlContainer {
    /**
     *
     */
    public function __construct() {
        parent::__construct('a');
        $this->setEndTagRequired(true);
    }

    /**
     * sets the href attribute
     * @param string $value
     */
    public function setHref($value) {
        $this->attributes->set('href', $value);
    }
    

    /**
     * gets the href attribute
     * @return string
     */
    public function getHref() {
        return $this->attributes->get('href');
    }

    /**
     * adds an anchor to the href attribute
     * @param string $anchor
     */
    public function addAnchor($anchor) {
        $this->setHref($this->getHref() .'#'.$anchor);
    }

    /**
     * create a url for a page
     * @param string $page
     * @param array $param
     * @return string
     */
    public static function createHref($page , array $param=array()) {
        return $page. self::createHrefQueryString($param);
    }

    /**
     * creates a query string
     * @param array $param
     * @return string
     */
    public static function createHrefQueryString(array $param) {
        $first = true;
        $urlParams = '';
        foreach($param as $key => $value) {
            if($first) {
                $urlParams .= '?'. $key.'='. $value;
                $first=false;
            }
            else {
                $urlParams .= '&'.$key.'='.$value;
            }

        }
        // TODO: replace other important chars
        $urlParams = str_replace('&', '&amp;', $urlParams);
        return  $urlParams;
    }

    public static function getParametersFromHref($href){
        $pos = strpos($href, '?');
        $queryString  = '';
        if($pos!==false){
           $queryString = substr($href, $pos  + 1);
        }
        else {
           $queryString = $href;
        }
        return self::getParametersFromQueryString($queryString);
    }
    public static function getParametersFromQueryString($queryString){
       $parameters = array();
       $parts = split("&", $queryString);
       foreach($parts as $part){
           list ($key, $value) = split('=', $part);
           $parameters[$key] = $value;
       }
       return $parameters;
    }



}

?>
